client 생성


In [66]:
import boto3

In [67]:
ec2 = boto3.resource('ec2') #high level client

In [68]:
instances = ec2.instances.all()

In [69]:
for i in instances:
    print(i)


ec2.Instance(id='i-0cda56764352ef50e')
ec2.Instance(id='i-0e0c4fa77f5a678b2')
ec2.Instance(id='i-07e52d2fbc2ebd266')
ec2.Instance(id='i-0d022de22510a69b7')
ec2.Instance(id='i-0e701a6507dbae898')

In [70]:
i1 = ec2.Instance(id='i-0cda56764352ef50e')

In [72]:
tag = i1.tags
print(tag)


[{'Key': 'Environment', 'Value': 'production'}, {'Key': 'Name', 'Value': 'june-prod-NAT'}]

In [73]:
next((t['Value'] for t in i1.tags if t['Key'] == 'Name'), None)


Out[73]:
'june-prod-NAT'

In [74]:
b = next((t['Value'] for t in i1.tags if t['Key'] == 'dd'), None)
print(b)


None

In [75]:
def findTag(instance, key, value):
    tags = instance.tags
    if tags is None:
        return False        
    tag_value = next((t['Value'] for t in tags if t['Key'] == key), None)
    return tag_value == value

In [76]:
findTag(i1,'Name', value='tt')


Out[76]:
False

In [77]:
findTag(i1,'Name', value='june-prod-NAT')


Out[77]:
True

In [78]:
findTag(i1,'d', value='june-prod-NAT')


Out[78]:
False

In [84]:
for i in instances:
    print(i.instance_id, findTag(i, 'Stop', 'auto'))


i-0cda56764352ef50e False
i-0e0c4fa77f5a678b2 True
i-07e52d2fbc2ebd266 False
i-0d022de22510a69b7 False
i-0e701a6507dbae898 False